use bevy_ecs::system::{Query, NonSendMut, Res, ResMut};

use crate::{AliceContext, function::command::canvas2d::{Canvas2dCommand, TC}};

use super::{components::{SpriteRendererComponent, TransformComponent, Rigidbody2DComponent, CameraComponent}, world::{ AlicePhysicsWorld}, camera::SceneCamera};

pub fn render_sprite(
    query: Query<(&SpriteRendererComponent, &TransformComponent)>,
    mut ctx: NonSendMut<AliceContext>,
) {
    for (sprite, transform) in &query {
       
        ctx.draw_canvas_command(Canvas2dCommand::QuadWithTC(TC {
            transform: transform.get_transform(),
            color: sprite.color,
        }))
    }
}


pub fn physics_system(
    mut query: Query<(&mut TransformComponent, &Rigidbody2DComponent)>,
    world: Res<AlicePhysicsWorld>,
) {
    for (mut transform, rigidbody) in &mut query {
        let body = &world.rigid_body_set[rigidbody.body_handle];

        let translation = body.translation();
        transform.translation.x = translation.x;
        transform.translation.y = translation.y;
       
        let rotation = body.rotation();

        transform.rotation.z = rotation.angle();

    }
}


pub fn camera_system(
    query: Query<(&TransformComponent, &CameraComponent)>,
    mut primary_camera: ResMut<SceneCamera>,
) {
    for (transform, _) in &query {

        let transform = transform.get_transform();
        let view = transform.inverse();
        primary_camera.set_view(view);

    }
}

